import sys
import os

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from concurrent.futures import ThreadPoolExecutor
import asyncio

from common.database import init_db
from letter.config import current_config
from letter.routes.letter_routes import (
    router as letter_router,
    set_global_variables as set_letter_variables,
)
from letter.routes.monitor_routes import (
    router as monitor_router,
    set_global_variables as set_monitor_variables,
)

# 创建线程池
thread_pool = ThreadPoolExecutor(max_workers=10)
# 创建调用记录字典
call_records = {}


async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    # 只在主进程中初始化数据库，避免热重载时重复初始化
    if not os.environ.get("UVICORN_RELOAD_PROCESS"):
        print("🚀 主进程启动，初始化数据库...")
        init_db(current_config.get("database_url", ""))
    else:
        print("🔄 热重载进程启动，跳过数据库初始化...")

    # 设置路由模块的全局变量
    set_letter_variables(call_records, thread_pool)
    set_monitor_variables(call_records, thread_pool)

    yield


app = FastAPI(title="来信件处理API", version="1.0.0", lifespan=lifespan)

# 挂载静态文件目录
static_files_dir = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "static"
)
app.mount("/static", StaticFiles(directory=static_files_dir), name="static")


@app.get("/", include_in_schema=False)
async def get_letter_page():
    """获取来信件处理页面"""
    return FileResponse(os.path.join(static_files_dir, "laixin_index.html"))


@app.get("/monitor", include_in_schema=False)
async def get_monitor_page():
    """获取来信件监控页面"""
    return FileResponse(os.path.join(static_files_dir, "laixin_index.html"))


@app.get("/api", include_in_schema=False)
async def get_api_info():
    """获取API信息"""
    return {
        "service": "来信件处理API",
        "version": "1.0.0",
        "monitor_page": "/monitor",
        "api_docs": "/docs",
        "health_check": "/health",
    }


# 注册路由
app.include_router(letter_router)
app.include_router(monitor_router)


@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "service": "letter_processor"}


if __name__ == "__main__":
    import uvicorn

    print(f"正在启动来信件处理API...")
    print(f"服务地址: http://{current_config['host']}:{current_config['port']}")
    print(f"API文档: http://{current_config['host']}:{current_config['port']}/docs")
    print("按 Ctrl+C 停止服务")

    uvicorn.run(
        "letter.app:app",
        host=current_config["host"],
        port=current_config["port"],
        reload=True,
    )
